package com.example.springsecuritycsrf.config;

import com.example.springsecuritycsrf.filter.HttpServletRequestWrapFilter;
import com.example.springsecuritycsrf.filter.SimpleAuthenticationFilter;
import com.example.springsecuritycsrf.filter.SimpleAuthorizationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.csrf.CsrfFilter;

import javax.servlet.http.HttpServletRequestWrapper;

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private CsrfTokenRedisRepository csrfTokenRedisRepository;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private SimpleAuthorizationFilter simpleAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()
                .withUser("JohnConnor")
                .password(passwordEncoder.encode("123456"))
                .authorities("ADMIN");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().ignoringAntMatchers("/login").csrfTokenRepository(csrfTokenRedisRepository)
                .and()
                .authorizeRequests()
                .anyRequest().hasAuthority("ADMIN")
                .and()
                .formLogin().disable()
                .addFilterBefore(new HttpServletRequestWrapFilter(), CsrfFilter.class)
                .addFilterAt(new SimpleAuthenticationFilter(authenticationManager(),redisTemplate), UsernamePasswordAuthenticationFilter.class)
                /*.addFilterAfter(new SimpleAuthorizationFilter(),CsrfFilter.class)*/
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
